package com.lf.web.service.system.user;

import com.lf.data.search.Field;
import com.lf.web.service.KeyUpdate;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import com.lf.web.service.system.role.Role;
import com.lf.web.service.system.role.RoleDAO;
import org.apache.log4j.Logger;

import java.util.List;

public class UserUpdateService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(UserUpdateService.class);
    private UserDAO userDAO;
    private RoleDAO roleDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    public String execute() {
        String type = form.getString("type");
        if ("role".equals(type)) {
            return role();
        } else {
            return update();
        }
    }

    private String update() {
        KeyUpdate keyUpdate = this.getKeyUpdate(User.class);
        LOGGER.debug("修改信息信息：" + keyUpdate);
        if (keyUpdate.check()) {
            int result = ResponseCode.FINISH;
            try {
                userDAO.update(keyUpdate);
            } catch (Exception e) {
                result = ResponseCode.FAILURE;
                LOGGER.error("用户信息修改异常：" + e);
            }
            ResponseInfo ri = new ResponseInfo(result);
            out(ri);
        } else {
            LOGGER.error("非法修改信息：" + keyUpdate);
            error(404);
        }
        return NONE;
    }

    private String role() {
        Field field = new Field();
        field.include(Role.ID, Role.NAME, Role.PARENT_ID);
        List roles = roleDAO.find(null, field, null);
        context.put("roles", roles);
        return "role";
    }
}
